<?php

namespace app\logic\api;

use app\api\models\think\MemberModel;
use cache\user\UserCache;
use support\Container;

/**
 * Class UserLogic
 * @package app\logic\api
 * @author ycr <Email: yuncran@126.com>
 */
class UserLogic
{
    /**
     * 是否开启缓存
     */
    const cache = false;

    /**
     *
     * @var UserCache userCache
     */
    public $userCache;

    public function __construct()
    {
        $this->userCache = Container::get(UserCache::class);
    }

    /**
     * 获取用户信息
     * @param int $uid
     * @return MemberModel|array|bool|mixed|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author ycr <Email: yuncran@126.com>
     */
    public function getUserInfo(int $uid)
    {
        if (!$user = $this->userCache->getUserCache($uid)) {
            $user = MemberModel::find(['uid' => $uid]);
            if (true === self::cache) $this->userCache->setUserCache($uid, json_encode($user));
        }
        return $user;
    }

    /**
     * 批量修改用户信息
     * @param int $uid
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author ycr <Email: yuncran@126.com>
     */
    public function userSave(int $uid, $data)
    {
        $user = MemberModel::find(['uid' => $uid]);
        $user->data($data, true);
        $user->save();
        $this->userCache->userClear($uid);
        return true;
    }

}